package com.bite.springblog.controller;


import com.bite.springblog.mapper.BlogInfoMappper;
import com.bite.springblog.model.BlogInfo;
import com.bite.springblog.model.Result;
import com.bite.springblog.model.UserInfo;
import com.bite.springblog.service.BlogService;
import com.bite.springblog.service.UserService;
import com.bite.springblog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private UserService userService;
    @Autowired
    private BlogInfoMappper blogInfoMappper;

    @RequestMapping("/getlist")
    public List<BlogInfo> getList(){
        return blogService.getBlogList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId,HttpServletRequest request){
        BlogInfo blogInfo= blogService.getBlogDetail(blogId);
        String token=request.getHeader("user_token");
        Integer userId=JwtUtils.getUserIdFromToken(token);
        if(userId!=null&&userId==blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }

    /**
     * 发布博客
     */
    @RequestMapping("/add")
    public Result publishBlog(String title,String content,HttpServletRequest request){
        String token=request.getHeader("user_token");
        Integer userId=JwtUtils.getUserIdFromToken(token);
        if(userId==null||userId<0){
            return Result.fail("用户未登录");
        }
        //插入博客
        BlogInfo blogInfo=new BlogInfo();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.insertBlog(blogInfo);
        return Result.success("success");
    }

    /**
     * 编辑博客
     */
    @RequestMapping("/update")
    public boolean updateBlog(Integer id,String title,String content){
        BlogInfo blogInfo=new BlogInfo();
        blogInfo.setId(id);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.updateBlog(blogInfo);
        return true;
    }

    /**
     * 删除博客
     */
    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        blogService.detele(blogId);
        return true;
    }
}
